package com.audi.activity;

import lib.relay.RelayInterface;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.audi.BaseActivity;
import com.audi.R;
import com.audi.activity.SigninActivity.Loader;
import com.audi.box.objects.Authen;
import com.audi.box.objects.LocalData;
import com.audi.box.service.ConnectService;
import com.audi.dto.MemberItem;
import com.audi.handler.JSonparse;
import com.audi.handler.TrippleDes;
import com.audi.view.BaseDeviceDialog;
import com.audi.view.DeviceUpdatePhoto;

public class PersonalPageActivity extends BaseActivity {
	private MemberItem mMemberItem;
	private TextView mUserName, mUserNameActionBar;
	private TextView mEmailMember;
	private TextView mLogOut;
	private ImageView mPersonalPageDrawer, editUserName;
	private ImageView mBtnEditMemberName;
	private RelativeLayout mChangePass;
	private ImageView imgAvataUser;
	private DeviceUpdatePhoto upPhoto;
	private Activity mActivity;
	private String m_Textoldpass;
	private String m_Textnewpass ;
	private ProgressDialog mDlgProgress = null;
	private String Tag2 = "PersonalPageActivity";
	private ProgressDialog pDialog;
	Context context;
	ProgressDialog progress;
	protected void onCreate(Bundle bundle) {
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(bundle);
		mActivity = this;

		setContentView(R.layout.activity_page_user);
		initData();
		initActionBar();
		setListenerPersonalPage();
		initView();
		// initActionBar(R.layout.action_bar_home_member);
	}

	private void initView() {
		mUserName = (TextView) findViewById(R.id.txt_user_name);
		mEmailMember = (TextView) findViewById(R.id.txt_email_of_member);
		imgAvataUser = (ImageView) findViewById(R.id.img_action_add_in_tab_device);
		mBtnEditMemberName = (ImageView) findViewById(R.id.btn_edit_username);
		mChangePass = (RelativeLayout) findViewById(R.id.rll_capability);
		editUserName = (ImageView) findViewById(R.id.btn_edit_username);
		mUserName.setText(LocalData.usergroup);
		// mUserNameActionBar.setText(mMemberItem.getMemberName());
		mEmailMember.setText(LocalData.usename);
		initListener();
	}

	private void initData() {
		mMemberItem = new MemberItem(0, "", "Scott Tsai",
				"scotttsai@gmail.com", 1, 0);

	}

	private void initListener() {
		mBtnEditMemberName.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// Code edit user name
			}
		});
		mChangePass.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				
				Toast.makeText(getApplicationContext(), "Change Password",
						Toast.LENGTH_SHORT).show();
				
				AlertDialog.Builder builder = new AlertDialog.Builder(PersonalPageActivity.this);
				builder.setTitle("Input your password and new password"); 
				 
				// Set up the input 
				final EditText input = new EditText(PersonalPageActivity.this);
				final EditText input2 = new EditText(PersonalPageActivity.this);
				input.setHint("Your Password");
				input2.setHint("Your New Password");
//				View mview = new View(PersonalPageActivity.this);
				LinearLayout lila1= new LinearLayout(PersonalPageActivity.this);
			    lila1.setOrientation(1); //1 is for vertical orientation
				// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text 
				input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); 
				
				
				input2.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); 
				
				lila1.addView(input);
			    lila1.addView(input2);
			    builder.setView(lila1); 
				// Set up the buttons 
				builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {  
				    @Override 
				    public void onClick(DialogInterface dialog, int which) {
				    	m_Textoldpass = input.getText().toString();
				    	m_Textnewpass = input2.getText().toString();
				    	Loader aslogin = new Loader();
						 aslogin.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
//				    		JSONObject jslogin = new JSONObject();
//							JSONObject jslogin2 = new JSONObject();
//				    		try {								
//								String ecryptpass = TrippleDes.encrypt(input.getText().toString());
//								String ecryptnewpass = TrippleDes.encrypt(input2.getText().toString());
//								jslogin2.put(LocalData.TAG_PASS, ecryptpass);
//								jslogin2.put(LocalData.TAG_NEWPASS, ecryptnewpass);
//								jslogin2.put(LocalData.TAG_USERNAME, LocalData.usename);
////								jslogin2.put(LocalData.TAG_PASS, edtPasswordSignIn.getText()
////										.toString());
//								jslogin.put("tag",LocalData.TAG_CHANGEPASS);
//								jslogin.put("strjson",jslogin2);	
//								Log.d(Tag2, "Put Json-2: "+ ecryptpass +" Newpass: "+ecryptnewpass );
//								Log.i(Tag2, "JsonString: " + jslogin.toString());
//							} catch (JSONException e) {						
//								Log.e(Tag2, "JSON failed-3" + e);
//							}
//							ConnectService.mmTcpClient.sendMessage(jslogin.toString());
//							long startTime = System.currentTimeMillis();
////							progress = new ProgressDialog(PersonalPageActivity.this);
//							progress = ProgressDialog.show(PersonalPageActivity.this, "",
//								    "Please wait", true); 
//							try {
//								Log.d(Tag2, "Trước while" + LocalData.ischangedpass );				
//								while ((System.currentTimeMillis()-startTime)<5000)
//								{		
//									if (LocalData.ischangedpass == true ) 
//					  				
//										{
//										Log.d(Tag2,"Thoát while");
//										break;										
//										}
//					  				}
//					  		}
//							
//							catch(Exception e)
//							{
//								Log.e(Tag2,""+e);
//							}	
//							progress.dismiss();	
//							Log.e(Tag2,""+LocalData.ischangedpass);
//							if (LocalData.ischangedpass==true)
//							{
//								Toast.makeText(PersonalPageActivity.this, "Your pass is change", Toast.LENGTH_LONG).show();
//								Intent intlogin = new Intent(PersonalPageActivity.this,SigninActivity.class);
//								startActivity(intlogin);
//								finish();
//							}
//							else {
//								Toast.makeText(PersonalPageActivity.this, "Can not change your password", Toast.LENGTH_LONG).show();
//								return;
//							}
//							Log.d(Tag2, "JsonString: " + jslogin.toString());						
//						
				    	}
				    	
				}); 
				builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				    @Override 
				    public void onClick(DialogInterface dialog, int which) {
				        dialog.cancel();
				    } 
				}); 
				 
				builder.show();
			}
		});
		editUserName.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Toast.makeText(getApplicationContext(), "Change Name",
						Toast.LENGTH_SHORT).show();

				BaseDeviceDialog editNameDialog = new BaseDeviceDialog(
						mActivity);
				editNameDialog.editNameUser();
			}
		});

		// update photo user//
		imgAvataUser.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				upPhoto = new DeviceUpdatePhoto(mActivity);
				upPhoto.updatePhoto();
			}
		});
	}

	protected void initActionBar() {
		mPersonalPageDrawer = (ImageView) findViewById(R.id.btn_action_member_menu_more);
		mUserNameActionBar = (TextView) findViewById(R.id.txt_home_member);
		mUserNameActionBar.setText(LocalData.usename);
		mLogOut = (TextView) findViewById(R.id.txt_logout_user);
		mLogOut.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// Code logout member
//				CreateProgressDialog(getString(R.string.box_setting_disconnect_content));
//				RelayInterface.RelayDeInit();
//				Toast.makeText(getApplicationContext(), "Logout",
//						Toast.LENGTH_SHORT).show();
				Intent intlogout = new Intent(PersonalPageActivity.this,SigninActivity.class);
				startActivity(intlogout);
				finish();
			}
		});
		mPersonalPageDrawer.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!mDrawerLayout.isDrawerOpen(mDrawerList)) {
					mDrawerLayout.openDrawer(mDrawerList);
				} else {
					mDrawerLayout.closeDrawer(mDrawerList);

				}
			}
		});
	}

	@Override
	public void onRefreshData() {
		// mUserName = (TextView) findViewById(R.id.txt_user_name);
		mUserName.setText(mMemberItem.getMemberName());
		mUserNameActionBar.setText(mMemberItem.getMemberName());
	}

	/* important call on the activity ver3.0 Namnt16 */
	int tempActionResult;

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Intent myIntent = new Intent(this, ActivityReviewImageCrop.class);
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == 555) {
			upPhoto.dimissUpdate();
			Log.d("start crop", "dgfgfdgfdgdf");
			tempActionResult = 0;
		}
		if (resultCode == RESULT_OK) {
			// user is returning from capturing an image using the camera
			if (requestCode == upPhoto.cameraCapture) {
				upPhoto.performcrop(upPhoto.getPicUri());
				Log.d("start crop", "crop crop crop");
				tempActionResult = 1;
			} else if (requestCode == upPhoto.picCrop) {
				myIntent.putExtra("Req", upPhoto.getstatus());
				// myIntent.putExtra("activity",mActivity.getApplicationContext());
				this.startActivityForResult(myIntent, 555);

				Log.d("start crop", "reviview=====-''/////");
				tempActionResult = 0;
			}
			if (requestCode == upPhoto.pickFromFile) {
				tempActionResult = 2;
				upPhoto.setPicUri(data.getData());
				upPhoto.performcrop(upPhoto.getPicUri());
				Log.d("start crop", "pick  form file=====- " + tempActionResult);

			}
		} else {
			Log.d("close ", "======== close" + tempActionResult);
			// Toast.makeText(activity, "sssss", Toast.LENGTH_LONG).show();
			if (tempActionResult == 1) {
				upPhoto.camphoto();
				Log.d("stop", "''/////" + tempActionResult);
				tempActionResult = 0;
			}
			if (tempActionResult == 2) {
				// upPhoto.performcrop(upPhoto.getPicUri());
				upPhoto.picphoto();
				Log.d("stop", "''/////" + tempActionResult);
				tempActionResult = 0;
				// this.finish();
			}
		}
	}

	private void CreateProgressDialog(String strMessage) {
		mDlgProgress = new ProgressDialog(this);
		mDlgProgress.setTitle(getString(R.string.box_setting_disconnect_title));
		mDlgProgress.setMessage(strMessage);
		mDlgProgress.setIndeterminate(true);
		mDlgProgress.setCancelable(true);
		mDlgProgress.show();
	}

	private void DestroyProgressDialog() {
		if (mDlgProgress != null)
			mDlgProgress.dismiss();
	}

	private void CreateWarningDialog(String strMessage) {
		AlertDialog.Builder m_Builder = new AlertDialog.Builder(this);
		m_Builder.setTitle(getString(R.string.box_setting_disconnect_title));
		m_Builder.setMessage(strMessage);
		m_Builder.setPositiveButton("Ok",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
					}
				});
		m_Builder.create().show();
	}

	public String GetLogTag() {
		String strTag = "[personal page]";
		return strTag;
	}

	@Override
	public void LogoutFinished(final boolean bValue) {
		runOnUiThread(new Runnable() {
			public void run() {
				DestroyProgressDialog();
				Intent intent = new Intent(PersonalPageActivity.this,
						SigninActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);
				finish();
			}
		});
	}

	@Override
	public void CBDeInit(boolean bValue) {
		if (bValue == true) {
			Log.d(GetLogTag(),
					"[personal page.java] DeInit Relay successfully.");
			RelayInterface.LogoutRelayS();
		} else {
			runOnUiThread(new Runnable() {
				public void run() {
					DestroyProgressDialog();
					Log.d(GetLogTag(),
							"[personal page.java] Failed to DeInit Relay.");
					CreateWarningDialog("Failed to DeInit Relay");
				}
			});

		}
	}
	public void setListenerPersonalPage() {
		imvPersonalPage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (!mDrawerLayout.isDrawerOpen(mDrawerList)) {
					mDrawerLayout.openDrawer(mDrawerList);
				} else {
					mDrawerLayout.closeDrawer(mDrawerList);
				}
			}
		});
	}
	
	private Authen model = null;

	public class Loader extends AsyncTask<Void, Void, Authen> {
		@Override
		protected void onPreExecute() {	
			super.onPreExecute();
			pDialog = new ProgressDialog(PersonalPageActivity.this);
			pDialog.setMessage("Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
			Log.d(Tag2, "pdialog show");		
		}

		@Override
		protected Authen doInBackground(Void... arg0) {

			JSONObject jslogin = new JSONObject();
			JSONObject jslogin2 = new JSONObject();
			
			Log.d(Tag2, "Doinbackground");
			try {
		    		try {								
						String ecryptpass = TrippleDes.encrypt(m_Textoldpass);
						String ecryptnewpass = TrippleDes.encrypt(m_Textnewpass);
						jslogin2.put(LocalData.TAG_PASS, ecryptpass);
						jslogin2.put(LocalData.TAG_NEWPASS, ecryptnewpass);
						jslogin2.put(LocalData.TAG_USERNAME, LocalData.usename);
//						jslogin2.put(LocalData.TAG_PASS, edtPasswordSignIn.getText()
//								.toString());
						jslogin.put("tag",LocalData.TAG_CHANGEPASS);
						jslogin.put("strjson",jslogin2);	
						Log.d(Tag2, "Put Json-2: "+ ecryptpass +" Newpass: "+ecryptnewpass );
						Log.i(Tag2, "JsonString: " + jslogin.toString());
					} 
		    		catch (JSONException e) {						
						Log.e(Tag2, "JSON failed-3" + e);
					}
					ConnectService.mmTcpClient.sendMessage(jslogin.toString());
					long startTime = System.currentTimeMillis();
						Log.d(Tag2, "Trước while" + LocalData.ischangedpass );				
						while ((System.currentTimeMillis()-startTime)<5000)
						{		
							if (LocalData.ischangedpass == true ) 
			  				
								{
								Log.d(Tag2,"Thoát while");
								break;										
								}
			  				}
					Log.e(Tag2,""+LocalData.ischangedpass);
													
			}
			catch(Exception e)
			{
				
			}
			model =  JSonparse.getauthen(LocalData.strreceiver);
			return model;	
		}
		@Override
		protected void onPostExecute(final Authen model) {
			Log.i("TESTTROLW", "TESTTROLW: 9");
			super.onPostExecute(model);// sfsmdf
			pDialog.dismiss();
			try {
//				Log.d(Tag2,"in postexecute -1 " + LocalData.islogin);
//				Log.d(Tag2,"Info " + model.getSuccess() + "---" + model.getTag() + " | "+ model.getUser_group());
//				if (LocalData.islogin==true) {
////					if (!model.getSuccess())
////					{
////						alertmess("Đăng nhập thất bại" +model.getSuccess() );
////					}
////					else {
//					LocalData.usergroup = model.getUser_group();
//					Log.i(LocalData.TAG_LOGIN,"username: "+ model.getUser_name() + "--usergroup: "+ model.getUser_group());
//						Log.d(Tag2, "On pregress update - 5");	
//						Toast.makeText(PersonalPageActivity.this, "Đăng nhập thành công", Toast.LENGTH_SHORT).show();
//						Intent inhctr = new Intent(PersonalPageActivity.this,HomeControlActivity.class);
//						startActivity(inhctr);
//						finish();
////					}
//				} else {
//					alertmess("Đăng nhập thất bại \nVui lòng kiểm tra Tên và Mật khẩu đăng nhập");
//					}	
				if (LocalData.ischangedpass==true)
				{
					Toast.makeText(PersonalPageActivity.this, "Your pass is change", Toast.LENGTH_LONG).show();
					Intent intlogin = new Intent(PersonalPageActivity.this,SigninActivity.class);
					intlogin.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					intlogin.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
					startActivity(intlogin);
					LocalData.resetvarible();
					finish();
				}
				else {
					Toast.makeText(PersonalPageActivity.this, "Can not change your password", Toast.LENGTH_LONG).show();
					return;
				}
//				Log.d(Tag2, "JsonString: " + jslogin.toString());
			} catch (Exception e) {
				e.printStackTrace();
				alertmess("Đăng ký thất bại");
				Log.d(Tag2,"in postexecute -2 "+e);
			}
		}
		
	}
	void alertmess(String mess) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(mess).setTitle("Thông báo").setCancelable(false)
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						return;
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}
	void alertfailmess(String mess) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(mess).setTitle("Thông báo").setCancelable(false)
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						finish();
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}
}